import { createRouter, createWebHashHistory } from "vue-router";
import HomeView from "../views/HomeView.vue";
import { getToken } from "@/utils/token";
import { showConfirmDialog } from "vant";

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "home",
      component: HomeView,
      meta: {
        tabbarShow: true,
      },
    },
    {
      path: "/my",
      name: "my",
      component: () => import("../views/MyView.vue"),
      meta: {
        tabbarShow: true,
        // 标记一下是否需要的登录才能访问
        requiredLogin: true,
      },
    },
    {
      path: "/cart",
      name: "cart",
      component: () => import("../views/CartView.vue"),
      meta: {
        tabbarShow: true,
        // 标记一下是否需要的登录才能访问
        requiredLogin: true,
      },
    },
    {
      path: "/userInfoEdit",
      name: "userInfoEdit",
      component: () => import("../views/UserInfoEditView.vue"),
      meta: {
        tabbarShow: false,
        // 标记一下是否需要的登录才能访问
        requiredLogin: true,
      },
    },
    {
      path: "/cate",
      name: "cate",
      component: () => import("../views/CateView.vue"),
      meta: {
        tabbarShow: true,
      },
    },
    {
      path: "/detail",
      name: "detail",
      component: () => import("../views/DetailView.vue"),
    },
    {
      path: "/search",
      name: "search",
      component: () => import("../views/SearchResultView.vue"),
    },
    {
      path: "/login",
      name: "login",
      component: () => import("../views/LoginView.vue"),
    },
    {
      path: "/reg",
      name: "reg",
      component: () => import("../views/RegView.vue"),
    },
  ],
});
// c端-登陆权限
// 1-meta做标记
// 2-路由前置守卫判断

router.beforeEach((to) => {
  // 判断用户要访问的页面 是否需要登陆才能访问
  if (to.meta.requiredLogin === true) {
    //判断用户是否登陆了
    let token = getToken();
    if (!token) {
      //没有登陆
      // 没有的登录-弹出一个提示
      showConfirmDialog({
        title: "注意",
        message: "您没有登录，请登录",
      })
        .then(() => {
          // on confirm
          router.push("/login");
          // return { path: "/login" };
        })
        .catch(() => {
          // on cancel
        });
      // 拦截了
      return false;
    }
  }
});

export default router;
